package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by WF on 2019/9/19 9:59
 */
@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitSevice;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.查询所有吐槽列表
    @GetMapping
    public Result findAll(){
        //1.1)查询所有吐槽列表
       List<Spit> spits =  spitSevice.findAll();
       //1.2)返回结果
        return new Result(true,StatusCode.OK,"查询列表成功！",spits);
    }
    //2.根据吐槽id查询某个吐槽
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        //2.1)根据id查询吐槽
        Spit spit = spitSevice.findById(spitId);
        //2.2)返回
        return  new Result(true,StatusCode.OK,"查询单个吐槽成功！",spit);
    }
    //3.添加吐槽
    @PostMapping
    public Result add(@RequestBody Spit spit){
        //3.1)添加吐槽
        spitSevice.add(spit);
        //3.2)返回结果
        return new Result(true,StatusCode.OK,"添加吐槽成功！");
    }
    //4.修改吐槽
    @PutMapping("{spitId}")
    public Result update(@RequestBody Spit spit,@PathVariable String spitId){
        spit.set_id(spitId);
        //3.1)修改吐槽
        spitSevice.update(spit);
        //3.2)返回结果
        return new Result(true,StatusCode.OK,"修改吐槽成功！");
    }
    //4.修改吐槽
    @DeleteMapping("{spitId}")
    public Result delete(@PathVariable String spitId){
        //4.1)修改吐槽
        spitSevice.delete(spitId);
        //4.2)返回结果
        return new Result(true,StatusCode.OK,"删除吐槽成功！");
    }
    //5.根据上级id查询吐槽数据
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByParentId(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        //5.1)根据上级id查询吐槽列表
        PageResult<Spit> spitPageResult = spitSevice.findByParentId(parentid,page,size);
        //5.2)返回结果
        return new Result(true,StatusCode.OK,"查询吐槽成功！",spitPageResult);
    }
    //6.吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //6.0）避免重复点赞
        //① 从redis中取出指定key的数据
        String userid = "1234";
        Object obj = redisTemplate.opsForValue().get("thumbup_" + userid + "_" + spitId);
        //② 判断是否存在值，如果有，就证明点赞过
        if(obj != null){
           return new Result(false,StatusCode.REPERROR,"不能重复点赞！");
        }
        //6.1)修改点赞数
        spitSevice.updateThumbup2(spitId);
        //6.2)向redis中放一个标志
        redisTemplate.opsForValue().set("thumbup_" + userid + "_" + spitId,"1");
        //6.3)返回结果
        return new Result(true,StatusCode.OK,"点赞成功！");
    }
}
